#!/bin/bash

# Redis 服务器地址和端口
REDIS_HOST="127.0.0.1"
REDIS_PORT="6379"

# 测试的配置
TEST_COUNT=100000
TEST_DURATION=20  # 测试持续的时间（秒）

# 初始化总时间变量和成功响应计数器
total_time=0
success_count=0

# 记录开始时间
start_time=$(date +%s)

# 使用redis-cli工具发送PING命令并测量时间
for ((i=0; i<TEST_COUNT; i++)); do
    start_time_ns=$(date +%s%3N)  # 获取当前时间纳秒
    redis_response=$(redis-cli -h $REDIS_HOST -p $REDIS_PORT ping 2>/dev/null)
    end_time_ns=$(date +%s%3N)    # 获取当前时间纳秒

    # 检查redis-cli是否成功执行并返回 PONG
    if [[ $redis_response == "PONG" ]]; then
        # 计算命令执行时间（微秒）
        diff_time=$((end_time_ns - start_time_ns))
        diff_time_us=$((diff_time / 1000))  # 转换为微秒
        total_time=$((total_time + diff_time_us))  # 累加到总时间
        ((success_count++))  # 增加成功响应计数
    else
        echo "Test $i failed: Redis server did not respond as expected."
    fi

    # 检查是否达到测试持续时间
    current_time=$(date +%s)
    if (( (current_time - start_time) >= TEST_DURATION )); then
        break
    fi
done

# 计算平均响应时间（微秒）
if (( success_count > 0 )); then
    avg_time=$((total_time / success_count))
    echo "Average latency (latency.avg): $avg_time microseconds"
else
    echo "No successful tests completed to calculate average latency."
fi

# 计算吞吐量（命令/秒）
if (( TEST_DURATION > 0 )); then
    throughput=$((success_count / TEST_DURATION))
    echo "Throughput: $throughput commands per second"
else
    echo "Test duration is zero, cannot calculate throughput."
fi


